package com.rcloud.server.sealtalk.interceptor;


import com.alibaba.druid.util.StringUtils;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.rcloud.server.sealtalk.constant.ErrorCode;
import com.rcloud.server.sealtalk.constant.TokenConstant;
import com.rcloud.server.sealtalk.model.response.APIResultWrap;
import com.rcloud.server.sealtalk.util.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * <p>IJPay 让支付触手可及，封装了微信支付、支付宝支付、银联支付常用的支付方式以及各种常用的接口。</p>
 *
 * <p>不依赖任何第三方 mvc 框架，仅仅作为工具使用简单快速完成支付模块的开发，可轻松嵌入到任何系统里。 </p>
 *
 * <p>IJPay 交流群: 723992875</p>
 *
 * <p>Node.js 版: https://gitee.com/javen205/TNW</p>
 *
 * <p>微信支付拦截器</p>
 *
 * @author Javen
 */
@Slf4j
@Component
public class WebSocketInterceptor implements HandlerInterceptor {
    @Value("${sealtalk-config.token.secret}")
    private String tokenSecret;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("进入前置拦截器...");
        String authorization = request.getHeader(TokenConstant.AUTHENTICATION);
        // 1.校验token
        if (StringUtils.isEmpty(authorization)||!authorization.startsWith(TokenConstant.PREFIX)) {
            printUnauthorized(response);
            return false;
        }
        // 2. 去除Bearer前缀
        String token = authorization.substring(TokenConstant.PREFIX.length());
        // 3. 解析
        Claims claims = JwtUtils.parseToken(token,tokenSecret);
        if (claims == null) {
            printUnauthorized(response);
            return false;
        }
        //设置全局的用户信息
        String userId = claims.get("userId", String.class);
        request.setAttribute(TokenConstant.LOGIN_USER_KEY + userId,claims);
        return true;
    }

    /**
     * 该部分没有进入到mvc，无法使用自定义异常，需要从response返回
     *
     * @param response
     * @throws Exception
     */
    protected void printUnauthorized(HttpServletResponse response) throws Exception {
        response.setHeader("Content-Type", "application/json");
        response.setCharacterEncoding("UTF-8");
        response.setStatus(401);
        String result = new ObjectMapper().writeValueAsString(APIResultWrap.error(ErrorCode.JWT_AUTH_TOKEN_ERROR));
        response.getWriter().print(result);
    }

}